package com.qudian.pay.monitor.interceptor;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.qudian.pay.core.aop.BaseInterceptor;
import com.qudian.pay.core.runtime.ProductContextHolder;
import com.qudian.pay.mq.SendMessage;
import com.qudian.pay.mq.DefaultSendResult;
import com.qudian.pay.mq.producer.MQProducer;

/**
 * @Description: 服务摘要监控(异常方法、异常原因、时间、备注)
 * @ClassName: MonitorInterepter
 * @author gaoxiang
 * @date 2016年11月7日 下午4:01:33
 */
public class MonitorInterepter extends BaseInterceptor {
	
	private final static Logger logger = LoggerFactory.getLogger(MonitorInterepter.class);
	
	private MQProducer mQProducer;
	
	private String exSourceId;
	
	private String exSourceName;
	
	@Override
	public Object bizInvoke(MethodInvocation invocation) throws Throwable {
		Method method = invocation.getMethod();
		try {
			return invocation.proceed();
		} catch (Throwable e) {
			
			sendMessage(e, method);
			throw e;
		}
	}
	
	public void sendMessage(Throwable e, Method method) {
		Map<String, Object> data = Maps.newHashMapWithExpectedSize(9);
		data.put("requestId", ProductContextHolder.getProductContext().getRequestId());
		data.put("exSourceId", exSourceId);
		data.put("exSourceName", exSourceName);
		data.put("exMethod", method.getDeclaringClass().getName() + "." + method.getName());
		data.put("date", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		data.put("exception", e);
		data.put("remark", "这个异常不一般");
		// 捕捉到异常后发送到远程监控服务器
		SendMessage msg = new SendMessage();
		msg.setBizValue(data);
		try {
			logger.debug("发送MQ消息入参:" + JSON.toJSONString(msg));
			DefaultSendResult sendMessage = mQProducer.sendMessage("ex-monitor-topic", "ex-monitor-tag", msg);
			logger.debug("发送MQ消息出参:" + JSON.toJSONString(sendMessage));
		} catch (Exception ex) {
			logger.error("异常MQ发送失败", ex);
		}
	}
	
	
	public void setMQProducer(MQProducer mQProducer) {
		this.mQProducer = mQProducer;
	}
	
	public void setExSourceId(String exSourceId) {
		this.exSourceId = exSourceId;
	}
	
	public void setExSourceName(String exSourceName) {
		this.exSourceName = exSourceName;
	}
}
